<?php

namespace App\Http\Controllers\College\Merchant;

use App\Http\Controllers\BaseController;
use App\Http\Middleware\OpenShop\MerchantAppAuth;
use App\Service\College\CollegeExamService;
use App\Service\Cruise\Mission\CollegeInputService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class CollegeInputController extends BaseController
{
    public function lists(Request $request): JsonResponse
    {
        $pageSize = $request->get('pageSize', 20);
        $pageNum  = $request->get('pageNum', 1);
        $userId   = (int)MerchantAppAuth::$userId;
        $shopId   = (int)$request->header('shopId');

        return $this->success(CollegeExamService::lists($pageNum, $pageSize, $userId, $shopId));
    }

    public function detail(Request $request, int $cruiseOrderId): JsonResponse
    {
        return $this->success((new CollegeInputService($cruiseOrderId, MerchantAppAuth::$userId))->config());
    }

    public function start(Request $request, int $cruiseOrderId): JsonResponse
    {
        return $this->success((new CollegeInputService($cruiseOrderId, MerchantAppAuth::$userId))->start());
    }

    public function info(Request $request, int $cruiseOrderId): JsonResponse
    {
        return $this->success((new CollegeInputService($cruiseOrderId,
            MerchantAppAuth::$userId))->getInputObjectFill());
    }

    public function update(Request $request, int $cruiseOrderId): JsonResponse
    {
        $field  = (string)$request->get('field');
        $value  = $request->get('value');
        $userId = MerchantAppAuth::$userId;

        $this->validate($request, [
            'field' => 'required|string',
            'value' => 'required',
        ]);

        (new CollegeInputService($cruiseOrderId, $userId))->saveUserContentJson($field, $value);

        return $this->success();
    }

    public function submit(Request $request, int $cruiseOrderId): JsonResponse
    {
        // 提交
        $obj = (new CollegeInputService($cruiseOrderId, MerchantAppAuth::$userId));
        $obj->submitOrder();

        // 获取结果
        list($totalScore, $actualScore, $successScore, $examResult, $_) = $obj->scores();

        return $this->success(compact('totalScore', 'actualScore', 'successScore', 'examResult'));
    }
}
